package com.cloud.config.security;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.BeanIds;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import com.cloud.config.jwt.JwtAuthenticationTokenFilter;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;
    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(this.userDetailsService).passwordEncoder(passwordEncoder());//自定义userDetailsService认证
    }

    //BCrypt密码编码器
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
//        return new NoEncryptPasswordEncoder();//自定义密码验证
    }

    @Bean
    public IanAuthenticationSuccessHandler yeaAuthenticationSuccessHandler() {
        return new IanAuthenticationSuccessHandler();
    }

    @Bean(name = BeanIds.AUTHENTICATION_MANAGER)
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        // 忽略拦截静态资源
        web.ignoring().antMatchers("/css/**")
                .antMatchers("/js/**")
                .antMatchers("/images/**")
                .antMatchers("/lib/**")
                .antMatchers("/fonts/**")
                .antMatchers("/lang/**")
                .antMatchers("/login/**")
                .antMatchers("/login.html")
                //解决服务注册url被拦截的问题
                .antMatchers("/swagger-resources/**")
                .antMatchers("/v2/**")
                .antMatchers("/**/*.json");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) // 使用 JWT，关闭token
                .and()
                .httpBasic()
                // 未经过认证的用户访问受保护的资源
                .authenticationEntryPoint(new IanAuthenticationEntryPoint())

                .and()
                .authorizeRequests()
                .antMatchers("/login", "/auth/**").permitAll()
                //以 "/admin/" 开头的请求只能由拥有 ROLE_ADMIN角色的用户访问
                .antMatchers("/admin").hasRole("ADMIN")
                .antMatchers("/user").access("hasRole('USER') or hasRole('ADMIN') ")
                .anyRequest().authenticated()
                .and()

                .formLogin()
                .successHandler(yeaAuthenticationSuccessHandler())
                // 认证失败
                .failureHandler(new IanAuthenticationFailureHandler())
                .permitAll()

                .and()
                .logout()
                .logoutSuccessHandler(new IanLogoutSuccessHandler())
                .permitAll();
        // 记住我
        http.rememberMe().rememberMeParameter("remember-me")
                .userDetailsService(userDetailsService).tokenValiditySeconds(300);


        http.exceptionHandling()
                // 已经认证的用户访问自己没有权限的资源处理
                .accessDeniedHandler(new IanAccessDeniedHandler())
                .and().addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
    }


}